package com.lance.answer.question_export.gk_new;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lance.answer.dto.GkUser;
import com.lance.answer.dto.GkUserCourseInfo;
import com.lance.answer.gui.answer.Util;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.io.*;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * 学生的答题情况
 */
@Slf4j
public class GetGkCourseInfoTask extends Thread {


    private final String driverPath;
    private final LinkedBlockingDeque<GkUser> users;

    public GetGkCourseInfoTask(String driverPath, LinkedBlockingDeque<GkUser> users) {
        this.driverPath = driverPath;
        this.users = users;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (users.size() > 0) {
            GkUser gkUser = users.take();
            String userName = gkUser.getUsername();
            String password = gkUser.getPwd();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), users.size(), userName, password);
            System.err.println("执行任务11111");
            getUserCourseInfo(driverPath, gkUser);
        }

        if (users.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    public static void getUserCourseInfo(String driverPath,GkUser gkUser ) throws InterruptedException, IOException {

        String userName = gkUser.getUsername();
        String password = gkUser.getPwd();
        String teacherName = gkUser.getTeacher();
        boolean complete = false;
        String filePath = "libs//userCourseInfo//"+teacherName;
        for (File file : Objects.requireNonNull(new File(filePath).listFiles())) {
            if (file.getName().contains(userName)&&file.length()>10) {
                complete = true;
                break;
            }
        }
        if (complete) {
            return;
        }

        WebDriver driver = Util.getDriver(driverPath);
        try {
            String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
            driver.get(url);
            Thread.sleep(3000);
            Util.login(driver, userName, password);
            Util.switchToFirst(driver);

            List<GkUserCourseInfo> courseInfos = Lists.newArrayList();

            for (WebElement we : driver.findElement(By.id("zaixuekecheng"))
                    .findElements(By.className("media-body"))) {
                // 课程名称
                GkUserCourseInfo courseInfo = new GkUserCourseInfo();
                courseInfos.add(courseInfo);
                String mediaTitle = we.findElement(By.className("media-title")).getText();
                courseInfo.setCourseName(mediaTitle);
//            try {
//                for (WebElement wInfo : we.findElements(By.className("mb-1"))) {
//                    String info = wInfo.getText();
//                    if (!Strings.isNullOrEmpty(info) && info.contains("形考成绩")) {
//                        String scoreString = info.split(",")[1];
//                        int sore = Integer.parseInt(scoreString);
//                        courseInfo.setScore(sore);
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            }
            Thread.sleep(1000);
          //  FileUtils.write(new File("E:\\gk\\userCourseInfo\\" + username + ".json"), JSONObject.toJSONString(courseInfos, SerializerFeature.PrettyFormat), "utf-8");
      //      FileUtils.write(new File("libs//userCourseInfo//" + username + ".json"), JSONObject.toJSONString(courseInfos, SerializerFeature.PrettyFormat), "utf-8");
            FileUtils.write(new File("libs//userCourseInfo//"+teacherName+"//" + userName + ".json"), JSONObject.toJSONString(courseInfos, SerializerFeature.PrettyFormat), "utf-8");
        } catch (Exception e) {
            log.info("用户：{}登录发生错误",userName);
            e.printStackTrace();
        }
        Thread.sleep(10000);
        closeDriver(driver);

    }

    private static void closeDriver(WebDriver driver) {
        try {
            driver.close();
            driver.quit();
        } catch (Exception e) {

        }
    }


}
